/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.hyk.appcfg.wrapper.invoker;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.hyk.appcfg.wrapper.prefer.Preference;
import org.hyk.appcfg.wrapper.prefer.Preference.AppType;

/**
 *
 * @author Administrator
 */
public abstract class AppCfgTask {

    static final String FILE_SP = System.getProperty("file.separator");

    public abstract String getAction();

    public abstract void preExecute();
    protected AppType appType;
    protected String email;
    protected String passwd;
    protected String appDir;

    class PasswdInputStream extends InputStream {

        ByteArrayInputStream bis = new ByteArrayInputStream(passwd.getBytes());

        @Override
        public int read() throws IOException {
            return bis.read();
        }
    }

    public AppCfgTask(AppType appType, String email, String passwd, String appDir) {
        this.appType = appType;
        this.email = email;
        this.passwd = passwd;
        this.appDir = appDir;
    }

    public InputStream getPasswdInputStream() {
        return new PasswdInputStream();
    }

    public String[] buildCommand() {
        String appcfgCmd = appType.equals(AppType.JAVA) ? Preference.getJavaSDKAppCfgCmd() : Preference.getPythonSDKAppCfgCmd();
        ArrayList<String> command = new ArrayList<String>();
        switch (appType) {
            case JAVA: {
                command.add(appcfgCmd);
                break;
            }
            case PYTHON: {
                command.add("python");
                command.add(appcfgCmd);
                break;
            }
        }
        command.add("-e");
        command.add(email);
        command.add("--passin");
        if(!Preference.useHttps())
        {
            command.add("--insecure");
        }
        int proxyMode = Preference.getProxyMode();
        switch (proxyMode) {
            case Preference.HTTP_PROXY: {
                //command =  new String[]{appcfgCmd, "-e", email, "--passin", "--proxy=" + Preference.getProxy(),getAction(), appDir};
                command.add("--proxy=" + Preference.getProxy());
                break;
            }
            case Preference.HTTPS_PROXY: {
                command.add("--proxy_https=" + Preference.getProxy());
                break;
            }
        }
        String[] splits = getAction().split("\\s+");
        for(String s:splits)
        {
             command.add(s.trim());
        }
        command.add(appDir);
        String[] ret = new String[command.size()];
        command.toArray(ret);
        return ret;
    }
}
